﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Rhino.Commons;
using Rhino.Security.Interfaces;
using DomainModel.Abstract;


namespace WebUI.Security
{
    public class AuthorizationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Aunthenticated?

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }

            //Authorized?

            var user = IoC.Resolve<IUserRepository>().GetUser(filterContext.HttpContext.User.Identity.Name);
            var actionName = filterContext.RouteData.Values["action"];

            var operation = string.Format("/{0}/{1}", filterContext.Controller.GetType().Name.Substring(0, filterContext.Controller.GetType().Name.Length - 10), actionName);

            var authorizationService = IoC.Resolve<IAuthorizationService>();
            if (!authorizationService.IsAllowed(user, operation))
            {
                //Check wether the user is authorized to perform the action on the inherited
                //type of the controller
                //operation = string.Format("/{0}/{1}", filterContext.Controller.GetType().BaseType.BaseType.Name, actionName);
                //if (!authorizationService.IsAllowed(user, operation))
                //{
                    filterContext.Controller.TempData["ErrorMessage"] = string.Format("You are not authorized to perform operation: {0}", operation);
                    filterContext.Result = new HttpUnauthorizedResult();
                //}
            }
        }
    }
}
